//
//  UserInfoTableViewController.m
//  TenMinDemo
//
//  Created by Shawn Li on 2021/3/10.
//  Copyright © 2021 CYXiang. All rights reserved.
//

#import "UserInfoTableViewController.h"
#import "EditInfoViewController.h"
#import "UserInfoTabCell.h"
#import "UserIconEditTabCell.h"
#import "CYXBaseRequest.h"
#import "TZImagePickerController.h"

@interface UserInfoTableViewController ()<TZImagePickerControllerDelegate>
/// <#注释#>
@property (nonatomic, strong) NSArray *itemList;
@end

@implementation UserInfoTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configItemsInfo];
//    [LCNotifiCenter addObserver:self selector:@selector(refreshView) name:@"UserInfoUpdated" object:self];
    
    [LCNotifiCenter addObserver:self selector:@selector(refreshView) name:@"UserInfoUpdated" object:nil];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)setupUI{
    [super setupUI];
    self.title = LCLocalString(@"my_profile");
    [self.tableView registerNib:[UINib nibWithNibName:@"UserInfoTabCell" bundle:nil] forCellReuseIdentifier:@"UserInfoTabCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"UserIconEditTabCell" bundle:nil] forCellReuseIdentifier:@"UserIconEditTabCell"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}

- (void)refreshView{
    [self configItemsInfo];
    [self.tableView reloadData];
}

- (void)configItemsInfo{
    UserInfoModel *user = kAppDelegate.curUser;
    if (!user) {
        self.itemList = @[];
        return;
    }
    NSString *name = LCSafeStr(user.name);
    name = LCSafeStr(user.signature);

   self.itemList = @[
    @{@"title":LCLocalString(@"head_icon"),@"subTitle":@"",@"ishideArr":@(NO)},
    @{@"title":LCLocalString(@"edit_name"),@"subTitle":LCSafeStr(user.name),@"ishideArr":@(NO)},
    @{@"title":LCLocalString(@"edit_gxqm"),@"subTitle":LCSafeStr(user.signature),@"ishideArr":@(NO)},];

}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (!self.itemList.count) {
        return 0;
    }
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.itemList.count > 0) {
        return section ? self.itemList.count - 1 : 1;
    }    
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section) {
        return 60;
    }
    return 104;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell;
    NSDictionary *item;
    if (indexPath.section == 0) {
        item = self.itemList.firstObject;
        UserIconEditTabCell *iconCell = [tableView dequeueReusableCellWithIdentifier:@"UserIconEditTabCell"];
        [iconCell refresh:@{@"title":item[@"title"],@"icon":kAppDelegate.curUser.icon}];
        cell = iconCell;
    }else if (indexPath.section == 1){
        UserInfoTabCell *infoCell = [tableView dequeueReusableCellWithIdentifier:@"UserInfoTabCell"];
        item = self.itemList[indexPath.row + 1];
        [infoCell refresh:item];
        cell = infoCell;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section) {
        NSDictionary *item = self.itemList[indexPath.row + 1];
        EditInfoViewController *vc = LoadVCFormXib(EditInfoViewController);
        vc.pageTitle = item[@"title"];
        vc.plhText = @"请输入";
        LRWeakSelf(self)
        LRWeakSelf(vc)
        if (indexPath.row == 0) {
            vc.actionBlock = ^(NSInteger aFlag, NSString * _Nonnull text) {
                [weakself editInfo:1 text:text vc:weakvc];
            };
        }else if (indexPath.row == 1){
            vc.actionBlock = ^(NSInteger aFlag, NSString * _Nonnull text) {
                [weakself editInfo:2 text:text vc:weakvc];
            };
            
        }
        vc.countLimit = 16;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        [self editIcon];
  
    }
   
}

- (void)editIcon{
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    imagePickerVc.modalPresentationStyle = UIModalPresentationOverFullScreen;
    
    [imagePickerVc setNavLeftBarButtonSettingBlock:^(UIButton *leftButton){
        [leftButton setImage:[UIImage imageNamed:@"fh_w"] forState:UIControlStateNormal];
        [leftButton setImageEdgeInsets:UIEdgeInsetsMake(0, -10, 0, 20)];
    }];
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    imagePickerVc.showSelectBtn = NO;
    imagePickerVc.allowCrop = YES;
//        imagePickerVc.needCircleCrop = self.needCircleCropSwitch.isOn;
    // 设置竖屏下的裁剪尺寸
    NSInteger left = 30;
    NSInteger widthHeight = SCREEN_WIDTH - 2 * left;
    NSInteger top = (SCREENH_HEIGHT - widthHeight) / 2;
    imagePickerVc.cropRect = CGRectMake(left, top, widthHeight, widthHeight);
    imagePickerVc.scaleAspectFillCrop = YES;
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        [self editIcon:photos];
    }];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
    

}

- (void)editIcon:(NSArray *)images{
    if (!images.count) {
        return;
    }
    UIImage *img = images.firstObject;
    [self editIcon_net:img];
    
}

- (void)editIcon_net:(UIImage *)image{
//    NSData *fileData = UIImagePNGRepresentation(image);
    NSData *fileData = UIImageJPEGRepresentation(image, 0.3);
    NSArray *files = @[@{
            @"name":@"file",
            @"data":fileData,
            @"type":@"image/png",
            
        }];
    
    [CYXBaseRequest uploadFile:API_setUserIcon param:nil files:files resultClass:nil progress:^(id progress) {
        
    } success:^(id res) {
        if ([res isEqual: RequestErrorCode]) {
            
        }else{
            LCInfoHUD(@"操作成功", 1);
//            [vc.navigationController popViewControllerAnimated:YES];
            LCPostNotification(@"UserInfoNeedUpdate");
        }
        
        CYXLog(@"%@",res)
    } failure:^(NSError *error) {
        CYXLog(@"%@",error)
    }];
    
//        [CYXBaseRequest postWithUrl:API_setUserIcon param:param resultClass:nil success:^(id res) {
//            if ([res isEqual: RequestErrorCode]) {
//
//            }else{
//
//            }
//
//            CYXLog(@"%@",res)
//        } failure:^(NSError *error) {
//            CYXLog(@"%@",error)
//        }];
}


/// <#Description#>
/// @param type 1 昵称 2 签名
/// @param text 文字
/// @param vc 控制器
- (void)editInfo:(NSInteger)type text:(NSString *)text vc:(UIViewController *)vc{
    NSDictionary *param = type == 1 ? @{@"name":text} : @{@"signature":text};
    NSString *api = type == 1  ? API_setName : API_setSignature;
    [CYXBaseRequest postWithUrl:api param:param resultClass:nil success:^(id res) {
        if ([res isEqual: RequestErrorCode]) {
            
        }else{
            LCInfoHUD(@"操作成功", 1);
            [vc.navigationController popViewControllerAnimated:YES];
            LCPostNotification(@"UserInfoNeedUpdate");
        }
        
        CYXLog(@"%@",res)
    } failure:^(NSError *error) {
        CYXLog(@"%@",error)
    }];
    
}

@end
